<script setup>
	import {getCurrentInstance, onBeforeUnmount, onMounted, ref} from "vue";
	import {getToken} from "@/utils/auth";
	import {addDownload, getDownloadByKey, updDownload } from "@/api/download/index";
	import Editor from '@/components/RichText/index.vue'
	const { proxy } = getCurrentInstance();
	import emitter from "@/utils/mitt";
	
	const props = defineProps({
		rowId: {
			type: [Number, String],
			default: null
		}
	})
	
	const formData = ref({
		// 下载内容
		content: '',
		// 下载表-主键id
		id: null,
		// 是否展示
		isView: 1,
		// 富文本文件
		richFileIds: [],
		// 下载标题
		title: '',
		// 上传文件
		fileIds: [],
		fileUrl: null
	});
	const rules = ref({
		title: [{required: true, message: '请输入内容标题', trigger: 'blur'}],
		fileUrl: [{required: true, message: '请添加下载文件', trigger: 'blur'}],
	});
	
	const fileRichAction = import.meta.env.VITE_APP_BASE_API + "/download/addRichFile"
	const fileTitleAction = import.meta.env.VITE_APP_BASE_API + "/download/addFile"
	
	const donwloadFiles = ref([])
	const richFilesData = ref([])

	const uploadFirstPic = (response, file, fileList) => {
		if(response.code === 200) {
			formData.value.fileIds = [response.data.id]
			formData.value.fileUrl = response.data.accessUrl
			donwloadFiles.value = [response.data]
		}
	}
	const clearFirstPic = () => {
		formData.value.fileIds = []
		formData.value.fileUrl = null
		donwloadFiles.value = []
		proxy.$refs["uploadFirstPicRef"].clearFiles();
	}
	
	const getFormData = () => {
		const tempElement = document.createElement('div')
		formData.value.content = proxy.$refs["editorRef"].getCurrentValue()
		tempElement.innerHTML = formData.value.content
		const imgElements = tempElement.querySelectorAll('img')
		formData.value.richFileIds = [];
		if(imgElements.length > 0) {
			imgElements.forEach(item => {
				let itemTemp = richFilesData.value.find(file => file.accessUrl === item.currentSrc)
				formData.value.richFileIds.push(itemTemp.id)
			});
		}
		return formData.value
	}
	
	const getData = async () => {
		const res = await getDownloadByKey({id: props.rowId})
		try {
			if(res.code === 200) {
				const { files, richFiles, id, isView, type, title, content } = res.data
				formData.value.content = content
				donwloadFiles.value = files
				richFilesData.value = richFiles
				formData.value.id = id
				formData.value.isView = isView
				formData.value.type = type
				formData.value.title = title
				formData.value.fileIds = files.map(item => item.id)
				formData.value.fileUrl = files?.length ? files[0].accessUrl : null
				formData.value.richFileIds = richFiles.map(item => item.id)
			}
		}
		catch(e) {
			console.log(e);
		}
	}
	
	const submit = () => {
		proxy.$refs.elForm.validate(async valid => {
			if(valid) {
				const params = getFormData()
				console.log('params', params)
				if(params.title == null || params.title === '') return
				let res
				params.id !== null && params !== '' ? res = await updDownload(params) : res = await addDownload(params)
				try {
					if(res.code === 200) {
						proxy.$modal.msgSuccess('操作成功')
						cancel(true)
					}
					else {
						proxy.$modal.msgError(res.msg)
					}
					formData.value = {
						content: '',
						id: null,
						isView: 1,
						richFileIds: [],
						title: '',
						fileIds: [],
						fileUrl: null,
					}
					donwloadFiles.value = [];
					richFilesData.value = [];
					clearFirstPic()
				}
				catch(e) {
					console.log(e);
					proxy.$modal.msgError(JSON.stringify(e))
				}
			}
		})
	}
	
	const cancel = (ifSubmit = false) => {
		emitter.emit('closeEdit', ifSubmit)
	}
	
	onMounted(() => {
		if(props.rowId) {
			getData();
		}
		emitter.on('richTestFileList', (data) => {
			richFilesData.value = [...richFilesData.value, ...data]
			console.log(richFilesData.value);
		})
	})
	
	onBeforeUnmount(() => {
		emitter.off('richTestFileList')
	})
	
</script>

<template>
	<div class="dialogContent">
		<el-form
			ref="elForm"
			:model="formData"
			:rules="rules"
			label-width="80px"
			style="width: calc(100% - 20px)"
		>
			<el-form-item label="下载标题" prop="title" required>
				<el-input
					v-model="formData.title"
					clearable
					placeholder="请输入下载标题"
				></el-input>
			</el-form-item>
			<el-form-item label="下载文件" prop="fileUrl">
				<el-upload
					ref="uploadFirstPicRef"
					:action="fileTitleAction"
					:headers="{
						Authorization: 'Bearer ' + getToken()
					}"
					:limit="1"
					:on-remove="clearFirstPic"
					:on-success="uploadFirstPic"
					:show-file-list="false"
				>
					<el-button size="small" type="primary">点击上传</el-button>
					<el-button size="small" type="warning" @click.stop="clearFirstPic">清空上传</el-button>
				</el-upload>
			</el-form-item>
			<el-form-item v-if="donwloadFiles?.length > 0" prop="files">
				<span>{{ donwloadFiles[0].accessUrl || ''}}</span>
			</el-form-item>
			<el-form-item label="下载内容" prop="content">
				<Editor
					v-model="formData.content"
					:value="formData.content"
					:file-size="20"
					:max-height="500"
					:min-height="360"
					url="/download/addFile"
					style="width: 100%"
					ref="editorRef"
				/>
			</el-form-item>
			<el-form-item label="是否展示" prop="isView">
				<el-switch v-model="formData.isView" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
			</el-form-item>
		</el-form>
		<div class="buttonList">
			<el-button class="button" type="primary" @click="submit">提交</el-button>
			<el-button class="button" @click="cancel">取消</el-button>
		</div>
	</div>
</template>

<style lang="scss" scoped>
	.dialogContent {
		overflow: auto;
	}
	.buttonList {
		display: flex;
		justify-content: center;
		margin-top: 20px;
	}
</style>
